package com.body.park.user.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Map;

/**
 * @Author chaoxian.wu
 * @DATE 2022/4/27 22:19
 */
public class JwtUtil {
    //随机盐
    private static final String SIGN = "sdlnjcslkdlkvm";

    private static final int VALIDITY = 7;

    /**
     * 获取token
     *
     * @param map 需要在token中携带的信息
     * @return
     */
    public static String getToken(Map<String, String> map) {
        //配置jwt有效时间
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE, VALIDITY);
        //创建jwt的Builder
        JWTCreator.Builder builder = JWT.create();
        //payload
        map.forEach(builder::withClaim);
        //设置过期时间与签名
        String token = builder.withExpiresAt(instance.getTime()).sign(Algorithm.HMAC256(SIGN));
        System.out.println(token);
        return token;
    }

    /**
     * 验证token并返回token信息
     *
     * @param token token
     * @return 解析后的信息
     */
    public static DecodedJWT verify(String token) {
        return JWT.require(Algorithm.HMAC256(SIGN)).build().verify(token);
    }
}
